<template>
  <div class="level-editor">
    <el-container>
      <el-main>
        <div class="editor-content">
          <el-row :gutter="24">
            <el-col :span="24">
              <h1 class="page-title">关卡编辑器</h1>
            </el-col>
          </el-row>

          <el-row :gutter="24">
            <!-- 左侧表单 -->
            <el-col :xs="24" :lg="8">
              <el-card class="form-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>关卡信息</span>
                  </div>
                </template>

                <el-form :model="level" label-width="100px" label-position="top">
                  <el-form-item label="关卡标题">
                    <el-input
                        v-model="level.title"
                        placeholder="请输入关卡标题"
                        clearable
                    />
                  </el-form-item>

                  <el-form-item label="难度等级">
                    <el-select v-model="level.difficulty" placeholder="请选择难度" style="width: 100%">
                      <el-option label="简单" :value="1" />
                      <el-option label="中等" :value="2" />
                      <el-option label="困难" :value="3" />
                    </el-select>
                  </el-form-item>

                  <el-form-item label="时间限制（秒）">
                    <el-input-number
                        v-model="level.timeLimit"
                        :min="10"
                        :max="300"
                        :step="10"
                        style="width: 100%"
                    />
                  </el-form-item>

                  <el-form-item label="上传图片">
                    <el-upload
                        class="upload-demo"
                        :action="uploadUrl"
                        :on-success="handleUploadSuccess"
                        :on-error="handleUploadError"
                        :before-upload="beforeUpload"
                        :show-file-list="false"
                        accept="image/*"
                    >
                      <el-button type="primary" :icon="Upload">点击上传</el-button>
                      <template #tip>
                        <div class="el-upload__tip">
                          只能上传jpg/png文件，且不超过2MB
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>

                  <el-divider />

                  <el-form-item>
                    <div class="error-spots-section">
                      <div class="section-header">
                        <span>错误点列表</span>
                        <el-tag type="info" size="small">{{ level.errorSpots.length }}</el-tag>
                      </div>
                      
                      <div class="error-spots-list" v-if="level.errorSpots.length > 0">
                        <el-card
                            v-for="spot in level.errorSpots"
                            :key="spot.id"
                            class="error-spot-card"
                            shadow="hover"
                        >
                          <div class="spot-content">
                            <div class="spot-info">
                              <div class="spot-description">{{ spot.description }}</div>
                              <div class="spot-position">
                                位置: ({{ spot.xCoordinate }}%, {{ spot.yCoordinate }}%)
                              </div>
                            </div>
                            <el-button
                                type="danger"
                                size="small"
                                :icon="Delete"
                                @click="removeSpot(spot.id)"
                                circle
                            />
                          </div>
                        </el-card>
                      </div>
                      
                      <el-empty v-else description="暂无错误点" :image-size="60" />
                    </div>
                  </el-form-item>

                  <el-form-item>
                    <el-button
                        type="primary"
                        size="large"
                        @click="saveLevel"
                        :loading="saving"
                        style="width: 100%"
                    >
                      保存关卡
                    </el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-col>

            <!-- 右侧图片编辑区域 -->
            <el-col :xs="24" :lg="16">
              <el-card class="image-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <span>图片编辑区域</span>
                    <el-tag v-if="level.imageUrl" type="success" size="small">已上传</el-tag>
                  </div>
                </template>

                <div class="image-editor-content">
                  <div v-if="level.imageUrl" class="image-container">
                    <img
                        ref="imageRef"
                        :src="`http://127.0.0.1:8080${level.imageUrl}`"
                        alt="关卡图片"
                        class="level-image"
                        @load="handleImageLoad"
                        @click="handleImageClick"
                    />

                    <!-- 显示错误点标记 -->
                    <div
                        v-for="spot in level.errorSpots"
                        :key="spot.id"
                        class="error-marker"
                        :style="{
                          left: `${spot.xCoordinate}%`,
                          top: `${spot.yCoordinate}%`
                        }"
                        :title="spot.description"
                        @click.stop="removeSpot(spot.id)"
                    >
                      <el-icon><Close /></el-icon>
                    </div>
                  </div>

                  <el-empty v-else description="请先上传图片" :image-size="100">
                    <el-button type="primary" @click="triggerUpload">上传图片</el-button>
                  </el-empty>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload, Delete, Close } from '@element-plus/icons-vue'

// 响应式数据
const level = reactive({
  title: '',
  imageUrl: '',
  difficulty: 1,
  timeLimit: 60,
  errorSpots: []
})

const imageLoaded = ref(false)
const imageSize = reactive({width: 0, height: 0})
const saving = ref(false)
const uploadUrl = '/dev-api/api/admin/upload-image'

// 模板引用
const imageRef = ref(null)

// 上传相关方法
const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  const isLt2M = file.size / 1024 / 1024 < 2

  if (!isImage) {
    ElMessage.error('只能上传图片文件!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  return true
}

const handleUploadSuccess = (response) => {
  console.log('上传响应:', response)
  if (response.code === 200 && response.data) {
    level.imageUrl = response.data
    ElMessage.success('图片上传成功!')
    console.log('图片URL设置为:', level.imageUrl)
  } else {
    ElMessage.error('上传失败：' + (response.message || '未知错误'))
  }
}

const handleUploadError = (error) => {
  console.error('上传错误:', error)
  ElMessage.error('上传失败，请重试')
}

const triggerUpload = () => {
  // 触发上传组件的点击事件
  document.querySelector('.el-upload input').click()
}

// 图片加载完成
const handleImageLoad = () => {
  console.log('图片加载完成') // 添加调试日志
  imageLoaded.value = true
  const img = imageRef.value
  imageSize.width = img.offsetWidth
  imageSize.height = img.offsetHeight
  console.log('图片尺寸:', imageSize) // 添加调试日志
}

// 点击图片添加错误点
const handleImageClick = async (e) => {
  console.log('图片被点击', { imageLoaded: imageLoaded.value })
  
  if (!imageLoaded.value) {
    ElMessage.warning('图片未加载完成，无法添加错误点')
    return
  }

  const rect = imageRef.value.getBoundingClientRect()
  const x = ((e.clientX - rect.left) / rect.width * 100).toFixed(2)
  const y = ((e.clientY - rect.top) / rect.height * 100).toFixed(2)

  console.log('点击坐标:', { x, y, rect })

  try {
    const { value: description } = await ElMessageBox.prompt('请输入错误描述', '添加错误点', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPattern: /.+/,
      inputErrorMessage: '错误描述不能为空'
    })

    const newSpot = {
      id: Date.now(),
      xCoordinate: parseFloat(x),
      yCoordinate: parseFloat(y),
      radius: 30,
      description
    }

    level.errorSpots.push(newSpot)
    ElMessage.success('错误点添加成功!')
    console.log('添加错误点:', newSpot)
  } catch {
    // 用户取消输入
  }
}

// 删除错误点
const removeSpot = async (spotId) => {
  try {
    await ElMessageBox.confirm('确定要删除这个错误点吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const index = level.errorSpots.findIndex(spot => spot.id === spotId)
    if (index > -1) {
      level.errorSpots.splice(index, 1)
      ElMessage.success('错误点删除成功!')
    }
  } catch {
    // 用户取消删除
  }
}

// 保存关卡
const saveLevel = async () => {
  if (!level.title) {
    ElMessage.warning('请填写关卡标题')
    return
  }
  if (!level.imageUrl) {
    ElMessage.warning('请上传关卡图片')
    return
  }
  if (level.errorSpots.length === 0) {
    ElMessage.warning('请至少添加一个错误点')
    return
  }

  saving.value = true
  const levelData = {
    ...level,
    totalSpots: level.errorSpots.length
  }

  console.log('保存关卡数据:', levelData)

  try {
    const response = await fetch('/dev-api/api/admin/level', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(levelData)
    })

    const result = await response.json()
    console.log('保存响应:', result)
    
    if (result.code === 200) {
      ElMessage.success('关卡保存成功!')
      // 重置表单
      Object.assign(level, {
        title: '',
        imageUrl: '',
        difficulty: 1,
        timeLimit: 60,
        errorSpots: []
      })
      imageLoaded.value = false
    } else {
      ElMessage.error('保存失败：' + (result.message || '未知错误'))
    }
  } catch (error) {
    console.error('保存错误:', error)
    ElMessage.error('保存失败：' + error.message)
  } finally {
    saving.value = false
  }
}
</script>

<style scoped>
.level-editor {
  background: #f5f7fa;
  min-height: 100vh;
  padding: 20px;
}

.editor-content {
  max-width: 1400px;
  margin: 0 auto;
}

.page-title {
  text-align: center;
  color: #303133;
  font-size: 32px;
  font-weight: bold;
  margin-bottom: 30px;
}

.form-card,
.image-card {
  margin-bottom: 20px;
  border-radius: 12px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  color: #303133;
}

.error-spots-section {
  width: 100%;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-weight: 600;
  color: #606266;
}

.error-spots-list {
  max-height: 300px;
  overflow-y: auto;
}

.error-spot-card {
  margin-bottom: 12px;
  border-radius: 8px;
}

.spot-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
}

.spot-info {
  flex: 1;
}

.spot-description {
  font-weight: 500;
  color: #303133;
  margin-bottom: 4px;
}

.spot-position {
  font-size: 12px;
  color: #909399;
}

.image-editor-content {
  text-align: center;
}

.image-container {
  position: relative;
  display: inline-block;
  border-radius: 8px;
  overflow: visible;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.level-image {
  max-width: 100%;
  height: auto;
  cursor: crosshair;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.level-image:hover {
  transform: scale(1.02);
}

.error-marker {
  position: absolute;
  width: 24px;
  height: 24px;
  background: #f56c6c;
  border: 2px solid #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 12px;
  cursor: pointer;
  transform: translate(-50%, -50%);
  transition: all 0.3s ease;
  box-shadow: 0 2px 8px rgba(245, 108, 108, 0.4);
  z-index: 10;
}

.error-marker:hover {
  background: #f78989;
  transform: translate(-50%, -50%) scale(1.2);
  box-shadow: 0 4px 12px rgba(245, 108, 108, 0.6);
}

.upload-demo {
  width: 100%;
}

:deep(.el-upload) {
  width: 100%;
}

:deep(.el-upload .el-button) {
  width: 100%;
}

@media (max-width: 768px) {
  .level-editor {
    padding: 10px;
  }
  
  .page-title {
    font-size: 24px;
    margin-bottom: 20px;
  }
  
  .error-spots-list {
    max-height: 200px;
  }
}
</style>